package cn.hist.hfp.service;

import cn.hist.hfp.converter.SpeciesConverter;
import cn.hist.hfp.entity.Species;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.SpeciesRepository;
import cn.hist.hfp.vo.SpeciesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SpeciesService {

    private final
    SpeciesRepository speciesRepository;

    private final
    SpeciesConverter speciesConverter;

    @Autowired
    public SpeciesService(SpeciesRepository speciesRepository, SpeciesConverter speciesConverter) {
        this.speciesRepository = speciesRepository;
        this.speciesConverter = speciesConverter;
    }

    public SpeciesVO findOne(int id) {
        Optional<Species> optionalSpecies = speciesRepository.findById(id);
        if (optionalSpecies.isPresent()) {
            return speciesConverter.convert(optionalSpecies.get());
        }
        throw new ResourceNotFoundException();
    }

    public List<SpeciesVO> findAll() {
        return speciesConverter.convert(speciesRepository.findAll());
    }

    public SpeciesVO create(Species pet) {
        return speciesConverter.convert(speciesRepository.saveAndFlush(pet));
    }

    public SpeciesVO update(Species pet) {
        return speciesConverter.convert(speciesRepository.saveAndFlush(pet));
    }

    public int delete(int id) {
        Optional<Species> optionalSpecies = speciesRepository.findById(id);
        optionalSpecies.ifPresent(speciesRepository::delete);
        return speciesRepository.findById(id).isPresent() ? 0 : 1;
    }
}
